package com.cyandpos.pad.offline.model;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.cyandpos.pad.R;
import com.cyandpos.pad.common.commondata.BaseResponse;
import com.cyandpos.pad.common.netmanager.PosHttpManager;
import com.cyandpos.pad.http.OkHttpUtils;
import com.cyandpos.pad.offline.bean.P_GetOffline;
import com.cyandpos.pad.offline.bean.ResultUpdateOffline;
import com.cyandpos.pad.offline.offlinedb.CursorUtil;
import com.cyandpos.pad.offline.offlinedb.Handler_Json;
import com.cyandpos.pad.offline.offlinedb.Sqldb;
import com.google.gson.JsonObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UpdateOffline {

   static TextView tv_title;
    static ProgressBar id_update_progress;
    static  TextView id_update_textview;
    static AlertDialog dialog;
    static int count=0;
    static int index=0;
    public static void getUpdate(final Sqldb sqldb, final Context context){
        index=0;
        count=0;
        Cursor cursor=sqldb.find("select * from POSDATADEF");
        List<P_GetOffline> list=new ArrayList<>();
        if(cursor!=null&&cursor.getCount()>0){
            while (cursor.moveToNext()){
                P_GetOffline offline=new P_GetOffline();
                offline.setKeyStr(CursorUtil.getString(cursor,"KEYSTR"));
                offline.setLocalTm(CursorUtil.getInt(cursor,"MAXTM"));
                offline.setTblName(CursorUtil.getString(cursor,"TBLMC"));
                offline.setSqlStr(CursorUtil.getString(cursor,"SQLSTR"));
                list.add(offline);
            }
            requst(list,sqldb,context);
            cursor.close();
        }
    }


public static  void requst(final List<P_GetOffline> list, final Sqldb sqldb, final Context context){
    PosHttpManager.updateOffline(list, new OkHttpUtils.ResultCallback() {
        @Override
        public void onSuccess(final JsonObject response) {
            showUpdateDialog(context);
           new Thread(new Runnable() {
               @Override
               public void run() {
                   BaseResponse<ResultUpdateOffline> baseResponse = BaseResponse.fromJson(response.toString(), ResultUpdateOffline.class);
                   if("0".equals(baseResponse.getCode())){
                       ResultUpdateOffline resultUpdateOffline=baseResponse.getData();
                       try {
                           if (resultUpdateOffline!= null) {
                               if(resultUpdateOffline.getRecordcount()!=0) {
                                   if(resultUpdateOffline.getData()!=null) {
                                       byte[] arr1 = CursorUtil.base64String2ByteFun(resultUpdateOffline.getData());
                                       byte[] arr2 = CursorUtil.uncompress(arr1);
                                       String result = new String(arr2, "GBK");
                                       HashMap<String, Object> hashMap = Handler_Json.JsonToCollection(result);
                                       count = hashMap.size();
                                       updateOffline(sqldb, hashMap, list,context);
                                   }else{
                                       if(dialog!=null){
                                           dialog.dismiss();
                                       }
                                   }
                               }else{
                                   if(dialog!=null){
                                       dialog.dismiss();
                                   }
                               }
                           }
                       } catch(IOException e){
                           e.printStackTrace();
                           Log.e("TAG", "e===" + e);
                       }
                   }else{
                       if(dialog!=null){
                           dialog.dismiss();
                       }
                   }
               }
           }).start();
        }
        @Override
        public void onFailure(String msg) {
            Log.e("TAG", "msg==="+msg);
            if(dialog!=null){
                dialog.dismiss();
            }
        }
    });
}

 public static void updateOffline(Sqldb sqldb, HashMap<String, Object> hashMap, List<P_GetOffline> list, final Context context){
     for (Map.Entry<String, Object> entry : hashMap.entrySet()) {
         index++;
         String table = entry.getKey();
         sendTable(table);
         List<String> nameList = new ArrayList<>();
         Cursor tableCursor = sqldb.find("SELECT * FROM " + table + " WHERE 0");
         try {
             String[] columnNames = tableCursor.getColumnNames();
             for (String s : columnNames) {
                 nameList.add(s);
             }
             tableCursor.close();
         } catch (Exception e) {
             e.printStackTrace();
             tableCursor.close();
         }
         String keystr="";
         for(int x=0;x<list.size();x++){
             if(list.get(x).getTblName().equals(table)){
                 keystr=list.get(x).getKeyStr();
             }
         }
         String[] keys = keystr.split(",");
         List<HashMap<String, Object>> listHashMap = (List<HashMap<String, Object>>) entry.getValue();
          int tm=0;
         for (int i = 0; i < listHashMap.size(); i++) {
             HashMap<String, Object> map = listHashMap.get(i);
             String t=map.get("TM")+"";
             if(t!=null&&!"".equals(t)&&!"null".equals(t)){
                 tm=tm>Integer.parseInt(t)?tm:Integer.parseInt(t);
             }
             String key = "";
             String[] valuesWhere = new String[keys.length];
             for (int j = 0; j < keys.length; j++) {
                 valuesWhere[j] = map.get(keys[j]) + "";
                 if (j == keys.length - 1) {
                     key = key + keys[j] + "=?";
                 } else {
                     key = key + keys[j] + "=? and ";
                 }
             }
             send(listHashMap.size(),i+1);
             ContentValues values = new ContentValues();
             for (Map.Entry<String, Object> entry1 : map.entrySet()) {
                 if (nameList.contains(entry1.getKey())) {
                     values.put(entry1.getKey(), entry1.getValue() + "");
                 }
             }
             boolean isInsert = sqldb.insert(table, values);
             if (!isInsert) {
                 boolean ispdate = sqldb.update(table, values, key, valuesWhere);
             }
         }
         ContentValues values = new ContentValues();
         values.put("MAXTM", tm);
         boolean ispdate = sqldb.update("POSDATADEF", values,"TBLMC=?", new String[]{table+ ""});
     }
 }

 public static  void showUpdateDialog(Context context){
     AlertDialog.Builder builder=new AlertDialog.Builder(context);
      dialog=builder.create();
     //dialog.setCancelable(false);
     View view= LayoutInflater.from(context).inflate(R.layout.dialog_update_db,null);
      tv_title=view.findViewById(R.id.tv_title);
     id_update_progress=view.findViewById(R.id.id_update_progress);
     id_update_textview=view.findViewById(R.id.id_update_textview);
     dialog.setView(view,0,0,0,0);
     dialog.show();
 }

    /**
     * 更新下载进度条的方法
     */
    static Handler mUpdateProgressHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    // 更新进度框
                    id_update_progress.setProgress(msg.arg1);
                    id_update_textview.setText(msg.arg1 + "%");
                    if(index==count&&msg.arg1==100){
                        if(dialog!=null){
                           dialog.dismiss();
                        }
                    }
                    break;
                case 2:
                    tv_title.setText("正在更新"+msg.obj+"表数据");
                    break;
            }
        }
    };

    public static void send(int count,int index){
        Message message=Message.obtain();
        message.what=1;
        message.arg1= (int) (((float) index / count) * 100);
        mUpdateProgressHandler.sendMessage(message);
    }

    public static void sendTable(String table){
        Message message=Message.obtain();
        message.what=2;
        message.obj=table;
        mUpdateProgressHandler.sendMessage(message);
    }
}
